package org.keqinglee.study.queue;

import java.time.LocalTime;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author: liqing
 * @date: 2021/11/8
 */
public class BlockingQueueTest {

    @SuppressWarnings("all")
    public static void main(String[] args) {
        BlockingQueue<String> queue = new LinkedBlockingQueue<>(10);

        //Producer
        new Thread(() -> {
            System.out.println("生产者开始执行");
            Random random = new Random();
            try {
                for (int i = 0; i < 60; i++) {
                    Thread.sleep(random.nextInt(5000));
                    queue.put(LocalTime.now().toString() + " i=" + i);
                }
            } catch (InterruptedException ex) {
                System.out.println("生产者异常");
            }
        }).start();

        //Consumer
        new Thread(() -> {
            System.out.println("消费者开始执行");
            try {
                while (true) {
                    //如果获取不到 则一直等待
                    String str = queue.take();
                    System.out.println(LocalTime.now().toString() + " " + str);
                }
            } catch (InterruptedException ex) {
                System.out.println("消费者异常");
            }
        }).start();
    }
}
